<template>
  <div class="site-wrapper site-page--login">
    <div class="site-content__wrapper">
      <div class="site-content--login">
        <div class="brand-info">
          <h2 class="brand-info__text">Personal Blog</h2>
          <p class="brand-info__intro">I love you more than you love me <br/> 要永远相信美好的事情即将发生</p>
        </div>
        <div class="login-main">
          <h3 class="login-title">后台管理系统</h3>
          <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" status-icon>
            <el-form-item prop="userName"><el-input v-model="dataForm.userName" placeholder="帐号" @blur="initCaptcha()" maxlength="30"></el-input></el-form-item>
            <el-form-item prop="password"><el-input v-model="dataForm.password" type="password" placeholder="密码" maxlength="30" show-password></el-input></el-form-item>
            <el-form-item prop="captcha">
              <el-row :gutter="20">
                <el-col :span="14"><el-input v-model="dataForm.captcha" placeholder="验证码" maxlength="5" :disabled="dataForm.captchDisabled"></el-input></el-col>
                <el-col :span="10" class="login-captcha" v-show="!dataForm.captchDisabled"><img :src="captchaPath" @click="getCaptcha()" /></el-col>
              </el-row>
            </el-form-item>
           <el-form-item>
              <el-row :gutter="140">
                <el-col :span="6"><el-checkbox v-model="dataForm.autoLogin">7天免登</el-checkbox></el-col>
                <el-col :span="5"><el-checkbox v-model="dataForm.remember">记住密码</el-checkbox></el-col>
                <el-col :span="10"><el-link class="site-link" type="primary" href="https://blog.beansprout.top">>>博客园</el-link></el-col>
              </el-row>
            </el-form-item>
            <el-form-item><el-button class="login-btn-submit" type="primary" @click="dataFormSubmit()">登录</el-button></el-form-item>
          </el-form>
          <footer-content class="footer-info"></footer-content>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { loginApi, getCaptchaApi } from '@/api/oauth'
import FooterContent from '@/components/common/footer-content'
import { localStorageSet, localStorageGet, localStorageRemove } from '@/utils/storage-util'
import ciphertext from '@/utils/ciphertext-util'
import { isLogin } from '@/utils/index'
export default {
  data() {
    return {
      dataForm: {
        userName: '',
        password: '',
        sourceType: 1,
        captcha: '',
        autoLogin: false,
        remember: false,
        captchDisabled: true
      },
      dataRule: {
        userName: [{ required: true, message: '帐号不能为空', trigger: 'blur' }],
        password: [{ required: true, message: '密码不能为空', trigger: 'blur' }],
        captcha: [{ required: true, message: '验证码不能为空', trigger: 'blur' }]
      },
      captchaPath: ''
    }
  },
  components: {
    FooterContent
  },
  created() {
    // 自动密码填充
    this.init()
    // 自动登录
    this.autoLogin()
  },
  methods: {
    // 获取验证码
    getCaptcha() {
      this.captchaPath = getCaptchaApi(this.dataForm)
      this.dataForm.captcha = ''
    },
    login() {
      loginApi(this.dataForm).then(res => {
        if (res && res.code === 10000) {
          let data = res.data
          let expiredTime = this.$time.formatDate(new Date().getTime() + (data.expiration * 1000), 'yyyy-MM-dd HH:mm:ss')
          this.$cookie.set('accessToken', data.accessToken, {
            'expires': expiredTime
          })
          this.$cookie.set('expiredTime', this.$time.YyMmDdToTimes(expiredTime))
          // 保存用户登录账户密码
          localStorageSet('USERNAME', this.dataForm.userName)
          if (this.dataForm.remember) {
            this.$cookie.set('refreshToken', data.refreshToken, 7)
            localStorageSet('PASSWORD', ciphertext.encode(this.dataForm.password))
          } else {
            this.$cookie.set('refreshToken', data.refreshToken, 1)
            localStorageRemove('PASSWORD')
          }
          localStorageSet('AUTOLOGIN', this.dataForm.autoLogin)
          localStorageSet('REMEMBER', this.dataForm.remember)

          let redirect = this.$route.query.redirectUrl
          if (redirect && redirect !== '/' && redirect.indexOf('home') === -1) {
            redirect = redirect.replace('%2F', '/')
            if (redirect.indexOf('=') !== -1) {
              redirect = redirect.substring(redirect.indexOf('=') + 1)
            }
            this.$router.push(redirect.substring(redirect.indexOf('/') + 1))
          } else {
            this.$router.replace({ name: 'home' })
          }
        } else {
          this.getCaptcha()
          this.$message.error(res.error)
        }
      }).catch(() => {
        this.getCaptcha()
        localStorageSet('AUTOLOGIN', false)
        this.dataForm.autoLogin = false
      })
    },
    // 提交表单
    dataFormSubmit() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          this.login()
          localStorageSet('AUTOLOGIN_TIME', new Date().getTime())
        }
      })
    },
    // 初始化验证码
    initCaptcha() {
      if (this.dataForm.userName && this.dataForm.userName.length > 0) {
        this.dataForm.captchDisabled = false
        this.getCaptcha()
      } else {
        this.dataForm.captchDisabled = true
      }
    },
    // 初始化
    init() {
      this.dataForm.userName = localStorageGet('USERNAME')
      let autoLogin = localStorageGet('AUTOLOGIN')
      if (autoLogin === 'true') {
        this.dataForm.autoLogin = true
      }
      let remember = localStorageGet('REMEMBER')
      if (remember === 'true') {
        this.dataForm.remember = true
        this.dataForm.password = ciphertext.decode(localStorageGet('PASSWORD'))
      }
      this.initCaptcha()
    },
    // 自动登录
    autoLogin() {
      // 判断是否有token，有了自动登录
      if (!isLogin()) {
        this.$router.replace({ name: 'home' })
      }

      // 判断是否免登
      let autoLogin = localStorageGet('AUTOLOGIN')
      if (autoLogin !== 'true') {
        return
      }
      let autoLoginTime = localStorageGet('AUTOLOGIN_TIME')
      autoLoginTime = autoLoginTime !== undefined && autoLoginTime !== null ? parseInt(autoLoginTime) : 0
      let currentTime = new Date().getTime()
      if (currentTime - autoLoginTime > 604800 * 1000) {
        localStorageSet('AUTOLOGIN', false)
        this.dataForm.autoLogin = false
        return
      }

      if (this.repeatLogin()) {
        localStorageSet('AUTOLOGIN', false)
        this.dataForm.autoLogin = false
        return
      }

      this.login()
    },
    repeatLogin() {
      // 判断10秒内自动登录次数超过10次，取消自动登录，手动登录
      let autoLoginFirstTime = localStorageGet('AUTOLOGIN_FIRST_TIME')
      if (!autoLoginFirstTime) {
        localStorageSet('AUTOLOGIN_FIRST_TIME', new Date().getTime())
        localStorageSet('AUTOLOGIN_FIRST_COUNT', 1)
        return false
      }
      autoLoginFirstTime = autoLoginFirstTime !== undefined && autoLoginFirstTime !== null ? parseInt(autoLoginFirstTime) : 0
      let currentTime = new Date().getTime()
      if (currentTime - autoLoginFirstTime > 10 * 1000) {
        localStorageSet('AUTOLOGIN_FIRST_TIME', new Date().getTime())
        localStorageSet('AUTOLOGIN_FIRST_COUNT', 1)
        return false
      }

      let autoLoginFirstCount = parseInt(localStorageGet('AUTOLOGIN_FIRST_COUNT'))
      if (currentTime - autoLoginFirstTime <= 10 * 1000 && autoLoginFirstCount >= 5) {
        return true
      }

      localStorageSet('AUTOLOGIN_FIRST_COUNT', autoLoginFirstCount + 1)
      return false
    }
  }
}
</script>

<style lang="scss">
.site-wrapper.site-page--login {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  background-color: rgba(38, 50, 56, 0.6);
  overflow: hidden;
  &:before {
    position: fixed;
    top: 0;
    left: 0;
    z-index: -1;
    width: 100%;
    height: 100%;
    content: '';
    background-image: url('~@/assets/img/login_bg.jpg');
    background-size: cover;
  }
  .site-content__wrapper {
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    padding: 0;
    margin: 0;
    overflow-x: hidden;
    overflow-y: auto;
    background-color: transparent;
  }
  .site-content--login {
    position: absolute;
    width: 1002px;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    -webkit-transform: translate(-50%, -50%);
  }
  .brand-info {
    float: left;
    zoom: 1;
    color: #fff;
    padding: 80px 0px;
    width: 500px;
    min-height: 564px;
    background-color: #000;
    background-color: transparent;
  }
  .brand-info__text {
    margin: 0 0 22px 0;
    font-size: 48px;
    font-weight: 400;
  }
  .brand-info__intro {
    margin: 10px 0;
    font-size: 18px;
    line-height: 1.58;
    opacity: 0.7;
  }
  .login-main {
    float: left;
    zoom: 1;
    padding: 100px 60px 0px;
    width: 500px;
    min-height: 564px;
    background-color: #fff;
    box-shadow: 0px 20px 80px 0px rgba(0,0,0,0.3);
    -webkit-box-shadow: 0px 20px 80px 0px rgba(0,0,0,0.3);
  }
  .login-title {
    font-size: 16px;
  }
  .login-captcha {
    overflow: hidden;
    > img {
      width: 100%;
      cursor: pointer;
      height: 2.25rem;
    }
  }
  .login-btn-submit {
    width: 100%;
  }
  .site-link {
    line-height: 14px;
    &:after {
      text-decoration: none;
    }
  }
  .footer-info {
    margin-top: 100px;
  }
}
</style>
